/**
 * 路由预加载工具函数
 */

// 预加载缓存
const preloadCache = new Map()
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

/**
 * 获取当前用户信息
 */
export const getCurrentUser = () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('system-user') || '{}')
    return userInfo?.name || userInfo?.username
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

/**
 * 检查缓存是否有效
 */
const isCacheValid = (cacheKey) => {
  const cached = preloadCache.get(cacheKey)
  if (!cached) return false
  return Date.now() - cached.timestamp < CACHE_DURATION
}

/**
 * 设置缓存
 */
const setCache = (cacheKey, data) => {
  preloadCache.set(cacheKey, {
    data,
    timestamp: Date.now()
  })
}

/**
 * 获取缓存
 */
const getCache = (cacheKey) => {
  const cached = preloadCache.get(cacheKey)
  return cached ? cached.data : null
}

/**
 * 预加载知识管理数据
 */
export const preloadKnowledgeData = async (currentUser) => {
  if (!currentUser) return
  
  const cacheKey = `knowledge_${currentUser}`
  if (isCacheValid(cacheKey)) {
    console.log('使用缓存的知识管理数据')
    return getCache(cacheKey)
  }

  try {
    const api = await import('@/api/knowledge')
    const results = await Promise.allSettled([
      api.knowledgeSpaceApi.getSpaces(currentUser),
      api.documentApi.getRecentDocuments(currentUser)
    ])
    
    const data = {
      spaces: results[0].status === 'fulfilled' ? results[0].value : null,
      recentDocuments: results[1].status === 'fulfilled' ? results[1].value : null
    }
    
    setCache(cacheKey, data)
    console.log('知识管理数据预加载完成')
    return data
  } catch (error) {
    console.warn('预加载知识管理数据失败:', error)
    return null
  }
}

/**
 * 预加载首页数据
 */
export const preloadHomeData = async (currentUser) => {
  if (!currentUser) return
  
  const cacheKey = `home_${currentUser}`
  if (isCacheValid(cacheKey)) {
    console.log('使用缓存的首页数据')
    return getCache(cacheKey)
  }

  try {
    const api = await import('@/api/knowledge')
    const recentDocuments = await api.documentApi.getRecentDocuments(currentUser)
    
    const data = { recentDocuments }
    setCache(cacheKey, data)
    console.log('首页数据预加载完成')
    return data
  } catch (error) {
    console.warn('预加载首页数据失败:', error)
    return null
  }
}

/**
 * 预加载空间详情数据
 */
export const preloadSpaceDetailData = async (spaceId, currentUser) => {
  if (!spaceId || !currentUser) return
  
  const cacheKey = `space_${spaceId}_${currentUser}`
  if (isCacheValid(cacheKey)) {
    console.log('使用缓存的空间详情数据')
    return getCache(cacheKey)
  }

  try {
    const api = await import('@/api/knowledge')
    const spaceDetail = await api.knowledgeSpaceApi.getSpaceById(spaceId, currentUser)
    
    const data = { spaceDetail }
    setCache(cacheKey, data)
    console.log('空间详情数据预加载完成')
    return data
  } catch (error) {
    console.warn('预加载空间详情数据失败:', error)
    return null
  }
}

/**
 * 页面数据预加载主函数
 */
export const preloadPageData = async (route) => {
  const currentUser = getCurrentUser()
  if (!currentUser) return

  try {
    switch (route.name) {
      case 'Knowledge':
        return await preloadKnowledgeData(currentUser)
        
      case 'Home':
        return await preloadHomeData(currentUser)
        
      case 'SpaceDetail':
        if (route.params.spaceId) {
          return await preloadSpaceDetailData(route.params.spaceId, currentUser)
        }
        break
        
      default:
        console.log(`页面 ${route.name} 暂无预加载配置`)
    }
  } catch (error) {
    console.warn('预加载页面数据失败:', error)
  }
}

/**
 * 清理过期缓存
 */
export const clearExpiredCache = () => {
  const now = Date.now()
  for (const [key, value] of preloadCache.entries()) {
    if (now - value.timestamp > CACHE_DURATION) {
      preloadCache.delete(key)
    }
  }
}

/**
 * 清理所有缓存
 */
export const clearAllCache = () => {
  preloadCache.clear()
  console.log('所有预加载缓存已清理')
}

/**
 * 智能预加载 - 基于用户行为预测
 */
export const smartPreload = async () => {
  const currentUser = getCurrentUser()
  if (!currentUser) return

  // 预加载用户最常访问的页面数据
  const commonRoutes = ['Knowledge', 'Home']
  
  for (const routeName of commonRoutes) {
    try {
      switch (routeName) {
        case 'Knowledge':
          await preloadKnowledgeData(currentUser)
          break
        case 'Home':
          await preloadHomeData(currentUser)
          break
      }
    } catch (error) {
      console.warn(`智能预加载 ${routeName} 失败:`, error)
    }
  }
}